/**
  ******************************************************************************
  * @file    main.c
  * @author  MCU Application Team
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 Puya Semiconductor Co.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by Puya under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private define ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private user code ---------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void APP_SystemClockConfig(void);

static void APP_RTCClockConfig(void);
static void APP_IWDGInit(void);
static void APP_LPTIMInit(void);
static void APP_LPTIMEnableOneShot(void);
static void APP_EnterSleepMode(void);
static void APP_uDelay(uint32_t nus);
static void APP_ExitSleepMode(void);

/**
  * @brief  Main program.
  * @retval int
  */
int main(void)
{
  /* Configure system clock */
	LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_SYSCFG);
	LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);

	APP_SystemClockConfig();
	APP_RTCClockConfig();	
	
	LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_CRC);

  // Must to be call in the first
  app_ota_boot_check();

	APP_LPTIMInit();
	APP_LPTIMEnableOneShot();
	
	APP_IWDGInit();
	app_task_init();
	while (1)
	{
		app_task_run();
		
	  APP_EnterSleepMode();
		LL_PWR_EnableLowPowerRunMode();
		LL_LPTIM_Disable(LPTIM1);
		APP_uDelay(160);
		LL_LPTIM_Enable(LPTIM1);
		LL_LPTIM_StartCounter(LPTIM1, LL_LPTIM_OPERATING_MODE_ONESHOT);
		LL_LPM_EnableDeepSleep();
		__WFI();
		LL_LPM_EnableSleep();
		LL_IWDG_ReloadCounter(IWDG);
		APP_ExitSleepMode();
		//printf("Wake\n");
	}
}

/**
  * @brief  System clock configuration function
  * @param  None
  * @retval None
  */
static void APP_SystemClockConfig(void)
{
  /* Enable HSI */
  LL_RCC_HSI_Enable();
	LL_RCC_HSI_SetCalibFreq(LL_RCC_HSICALIBRATION_24MHz);
  while(LL_RCC_HSI_IsReady() != 1)
  {
  }

  /* Set AHB prescaler */
  LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);

  /* Configure HSISYS as system clock source */
  LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_HSISYS);
  while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSISYS)
  {
  }

  /* Set APB1 prescaler */
  LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1);
  LL_Init1msTick(24000000);

  /* Update system clock global variable SystemCoreClock (can also be updated by calling SystemCoreClockUpdate function) */
  LL_SetSystemCoreClock(24000000);
	LL_SYSTICK_EnableIT();
}

static void APP_RTCClockConfig(void)
{
  /*##-1- Enable PWR clock and enable access to the backup domain #######*/
  /* To change the source clock of the RTC functionalities (LSE, LSI), you have to:
      - Enable the PWR clock
      - Enable write access to configure the RTC clock source (once after reset).
      - Reset the Backup domain
      - Configure the needed RTC clock source */
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);

  LL_PWR_EnableBkUpAccess();
  LL_RCC_LSE_Enable();
}

static void APP_IWDGInit(void)
{
  LL_RCC_LSI_Enable();
  while (LL_RCC_LSI_IsReady() == 0U) {;}

  LL_IWDG_Enable(IWDG);
  LL_IWDG_EnableWriteAccess(IWDG);
  LL_IWDG_SetPrescaler(IWDG, LL_IWDG_PRESCALER_32); 
  // LL_IWDG_SetReloadCounter(IWDG, 1024); /* T*1024=1s */
  LL_IWDG_SetReloadCounter(IWDG, 3072); /* T*2048=2s */
  while (LL_IWDG_IsReady(IWDG) == 0U) {;}
  LL_IWDG_ReloadCounter(IWDG);
}

static void APP_LPTIMInit(void)
{
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_LPTIM1);
  /* Enable LSI */
  LL_RCC_LSI_Enable();
  
  /* Wait for LSI to be ready */
  while(LL_RCC_LSI_IsReady() == 0)
  {}
    
  /* Configure LSI as LPTIM clock source */
  LL_RCC_SetLPTIMClockSource(LL_RCC_LPTIM1_CLKSOURCE_LSI);
}

static void APP_LPTIMEnableOneShot(void)
{
  /* Configure LPTIM */
  /* LPTIM prescaler: divide by 32 */
  LL_LPTIM_SetPrescaler(LPTIM1,LL_LPTIM_PRESCALER_DIV32);
  
  /* Update ARR at the end of LPTIM counting period */
  LL_LPTIM_SetUpdateMode(LPTIM1,LL_LPTIM_UPDATE_MODE_ENDOFPERIOD);
  
  /* Enable ARR interrupt */
  LL_LPTIM_EnableIT_ARRM(LPTIM1);
  
  /* Enable NVIC interrupt request */
  NVIC_EnableIRQ(LPTIM1_IRQn);
  NVIC_SetPriority(LPTIM1_IRQn,7);
  
  /* Enable LPTIM */
  LL_LPTIM_Enable(LPTIM1);
  
  /* Configure auto-reload value: 51 */
  LL_LPTIM_SetAutoReload(LPTIM1,1024);
}

static void APP_EnterSleepMode(void)
{
  // 关闭SystemTick中断
  LL_SYSTICK_DisableIT();
}

static void APP_uDelay(uint32_t nus)
{
  __IO uint32_t Delay =1+ nus * (SystemCoreClock / 24U) / 1000000U;
  do
  {
    __NOP();
  }
  while(Delay--);
}

static void APP_ExitSleepMode(void)
{
  app_sys_ticks += LL_LPTIM_GetCounter(LPTIM1);
  LL_SYSTICK_EnableIT();
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
void APP_ErrorHandler(void)
{
  /* Infinite loop */
  while (1)
  {
  }
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     for example: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* Infinite loop */
  while (1)
  {
  }
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT Puya *****END OF FILE******************/
